﻿using Microsoft.EntityFrameworkCore;
using Ninesky.Entities;
using Ninesky.InterfaceService;
using System;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;


namespace Ninesky.Service
{
    public class BaseService<T> :InterfaceBaseService<T> where T:class
    {
        protected NineskyDbContext dbContext { get; set; }

        public BaseService(NineskyDbContext nineskyDbContext)
        {
            dbContext = nineskyDbContext;
        }

        public async virtual Task<OperationResult> AddAsync(T entity)
        {
            OperationResult operationResult = new OperationResult();
            await dbContext.Set<T>().AddAsync(entity);
            if(await dbContext.SaveChangesAsync() > 0)
            {
                operationResult.Succeed = true;
                operationResult.Message = "保存数据成功";
            }
            else
            {
                operationResult.Succeed = false;
                operationResult.Message = "保存数据失败";
            }
            return operationResult;

        }

        public async virtual Task<bool> AnyAsync(Expression<Func<T, bool>> expression)
        {
            return await dbContext.Set<T>().AnyAsync(expression);
        }

        public async virtual Task<OperationResult> UpdateAsync(T entity)
        {
            OperationResult operationResult = new OperationResult();
            dbContext.Set<T>().Update(entity);
            if (await dbContext.SaveChangesAsync() > 0)
            {
                operationResult.Succeed = true;
                operationResult.Message = "保存数据成功";
            }
            else
            {
                operationResult.Succeed = false;
                operationResult.Message = "保存数据失败";
            }
            return operationResult;
        }

        public async virtual Task<OperationResult> DeleteAsync(T entity)
        {
            OperationResult operationResult = new OperationResult();
            dbContext.Set<T>().Remove(entity);
            if (await dbContext.SaveChangesAsync() > 0)
            {
                operationResult.Succeed = true;
                operationResult.Message = "删除成功";
            }
            else
            {
                operationResult.Succeed = false;
                operationResult.Message = "删除失败";
            }
            return operationResult;
        }

        public async virtual Task<T> FindAsync(params object[] keyValues)
        {
            return await dbContext.Set<T>().FindAsync(keyValues);
        }

        public virtual IQueryable<T> FindList(Expression<Func<T, bool>> expression)
        {
            return dbContext.Set<T>().AsNoTracking().Where(expression);
        }

        public virtual IQueryable<T> FindList(Expression<Func<T, bool>> expression, string orderByString)
        {
            return dbContext.Set<T>().AsNoTracking().Where(expression).OrderBy(orderByString);
        }
    }
}
